<?php

namespace App\Trip\Geo;

use Illuminate\Support\Facades\Redis;

class RedisGeo
{
    private string $key;

    public function __construct(string $key)
    {
        $this->key = $key;
    }

    function addByLocation(string $location, $member): void
    {
        if (!$location) {
            return;
        }
        $location  = new Location($location);
        $longitude = $location->getLongitude();
        $latitude  = $location->getLatitude();
        $longitude && $latitude && $this->add($location, $location, $member);
    }

    /**
     *  geo add
     * @param string $longitude 经度
     * @param string $latitude 纬度
     * @param mixed  $member 成员
     * @return void
     */
    public function add(string $longitude, string $latitude, mixed $member)
    {
        if (!$latitude || !$longitude) {
            return;
        }
        return Redis::geoAdd($this->key, $longitude, $latitude, $member);
    }

    /**
     * 查找附近的成员
     * @param string $longitude
     * @param string $latitude
     * @param int    $distance
     * @param string $unit
     * @param int    $count
     * @param string $sort
     * @return array
     */
    public function radius(string $longitude, string $latitude, int $distance = 10, string $unit = 'km', int $count = 0, string $sort = 'ASC'): array
    {
//        $res = Redis::geoRadius($key, $longitude, $latitude, 200, 'km',['WITHDIST','count'=>1,'ASC']);
        $six = [
            'WITHDIST',
            $sort,
        ];

        if ($count > 0) {
            $six['count'] = $count;
        }
        $res = Redis::geoRadius($this->key, $longitude, $latitude, $distance, $unit, $six);
        if (!$res) {
            return [];
        }
        $data = [];
        foreach ($res as $re) {
            $data[$re[0]] = $re[1];
        }
        return $data;
    }

    /**
     * 量成员的距离
     * @param mixed  $member1
     * @param mixed  $member2
     * @param string $unit 默认单位为千米
     * @return float
     */
    public function distance(mixed $member1, mixed $member2, string $unit = 'km'): float
    {
        $distance = Redis::geoDist($this->key, $member1, $member2, $unit);
        return round($distance, 2);
    }

    /**
     * 删除某成员
     * @param mixed $member
     * @return void
     */

    public function delete(mixed $member)
    {
        return Redis::zrem($this->key, $member);
    }

    public function hash(mixed $member)
    {
        return Redis::geoHash($this->key, $member)[0] ?? false;
    }

}